# -*- coding: utf-8 -*-
##############################################################################
#
#    OpenERP, Open Source Management Solution
#    Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as
#    published by the Free Software Foundation, either version 3 of the
#    License, or (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
import xlwt
from .. import format_common
from openerp.tools.translate import _
import cStringIO
from openerp.osv import osv, fields
import os, time
import base64
import logging
_logger = logging.getLogger(__name__)
from xlwt import *

class param_gatepass_report(osv.osv_memory):
    _name = 'param.gatepass.report'
    _description = 'Gatepass Report'
    _columns = {
        'date_filter_selection': fields.selection([('none_sel','None'),('date_sel','Date')], 'Date Filter Selection'),
        'date_from': fields.date("From Date"),
        'date_to': fields.date("To Date"),
        'im_filter_selection': fields.selection([('all_vall','All'),('def','Default'),('input', 'Input'),('selection','Selection')],'GP Filter Selection', required=True),
        'im_def_from':fields.many2one('stock.picking', 'GP No From', domain=[('picking_type_id.code','=','internal'),('state','!=','cancel'),('gate_pass','=',True)], required=False),
        'im_def_to':fields.many2one('stock.picking', 'GP No To', domain=[('picking_type_id.code','=','internal'),('state','!=','cancel'),('gate_pass','=',True)], required=False),
        'im_input_from':fields.char('GP No From', size=128),
        'im_input_to':fields.char('GP No To', size=128),
        'im_no_ids' :fields.many2many('stock.picking', 'gatepass_report_internal_move_rel', 'report_id', 'im_id', 'GP No', domain=[('picking_type_id.code','=','internal'),('state','!=','cancel'),('gate_pass','=',True)]),
        'requestor_filter_selection': fields.selection([('all_vall','All'),('def','Default'),('input', 'Input'),('selection','Selection')],'Requestor Filter Selection', required=True),
        'requestor_def_from':fields.many2one('res.users', 'Requestor From', required=False),
        'requestor_def_to':fields.many2one('res.users', 'Requestor To', required=False),
        'requestor_input_from':fields.char('Requestor From', size=128),
        'requestor_input_to':fields.char('Requestor To', size=128),
        'requestor_name_ids' :fields.many2many('res.users', 'gatepass_report_requestor_rel', 'report_id', 'requestor_id', 'Requestor'),
        'project_filter_selection': fields.selection([('all_vall','All'),('def','Default'),('input', 'Input'),('selection','Selection')],'Project Filter Selection', required=True),
        'project_def_from':fields.many2one('project.project', 'Project From', domain=[('state', '!=', 'cancelled')], required=False),
        'project_def_to':fields.many2one('project.project', 'Project To', domain=[('state', '!=', 'cancelled')], required=False),
        'project_input_from': fields.char('Project From', size=128),
        'project_input_to': fields.char('Project To', size=128),
        'project_name_ids' :fields.many2many('project.project', 'gatepass_report_project_rel', 'report_id', 'project_id', 'Project', domain=[('state', '!=', 'cancelled')]),
        'cust_filter_selection': fields.selection([('all_vall','All'),('def','Default'),('input', 'Input'),('selection','Selection')],'Customer Filter Selection', required=True),
        'cust_def_from':fields.many2one('res.partner', 'Customer From', domain=[('customer','=',True)], required=False),
        'cust_def_to':fields.many2one('res.partner', 'Customer To', domain=[('customer','=',True)], required=False),
        'cust_input_from':fields.char('Customer From', size=128),
        'cust_input_to':fields.char('Customer To', size=128),
        'cust_name_ids' :fields.many2many('res.partner', 'gatepass_report_customer_rel', 'report_id', 'cust_id', 'Customer', domain=[('customer','=',True)]),
        'sortby_ids': fields.one2many('param.gatepass.report.sortby','sortby_id', 'Sort By'),
    }
    
    _defaults = {
        'date_filter_selection': 'none_sel',
        'im_filter_selection': 'all_vall',
        'requestor_filter_selection': 'all_vall', 
        'project_filter_selection': 'all_vall',
        'cust_filter_selection': 'all_vall',
    }
    
    def onchange_date_filter_selection(self, cr, uid, ids, date_filter_selection, context=None):
        if context is None:
            context = {}
        res = {}
        if date_filter_selection != 'none_sel':
             res['value'] = {'date_from': False, 'date_to': False, 
                                }
        return res
    
    def onchange_im_filter_selection(self, cr, uid, ids, im_filter_selection, context=None):
        if context is None:
            context = {}
        res = {}
        if im_filter_selection != 'all_vall':
             res['value'] = {'im_def_from': False, 'im_def_to': False, 'im_input_from': False, 'im_input_to': False, 'im_no_ids': False,
                                }
        return res
    
    def onchange_requestor_filter_selection(self, cr, uid, ids, requestor_filter_selection, context=None):
        if context is None:
            context = {}
        res = {}
        if requestor_filter_selection != 'all_vall':
             res['value'] = {'requestor_def_from': False, 'requestor_def_to': False, 'requestor_input_from': False, 'requestor_input_to': False, 'requestor_name_ids': False,
                                }
        return res
    
    def onchange_project_filter_selection(self, cr, uid, ids, project_filter_selection, context=None):
        if context is None:
            context = {}
        res = {}
        if project_filter_selection != 'all_vall':
             res['value'] = {'project_def_from': False, 'project_def_to': False, 'project_input_from': False, 'project_input_to': False, 'project_name_ids': False,
                                }
        return res
    
    def onchange_cust_filter_selection(self, cr, uid, ids, cust_filter_selection, context=None):
        if context is None:
            context = {}
        res = {}
        if cust_filter_selection != 'all_vall':
             res['value'] = {'cust_def_from': False, 'cust_def_to': False, 'cust_input_from': False, 'cust_input_to': False, 'cust_name_ids': False,
                                }
        return res
    
    def _search_data(self, cr, uid, ids, data_obj, val_data, filter_selection, default_from, default_to, input_from, input_to, selection_ids, context=None):

        data_header = ''
        data_ids = []

        if context is None:
            context = {}
        
        if filter_selection == 'all_vall':
            data_ids = data_obj.search(cr, uid, val_data, order='id ASC')
        if filter_selection == 'def':
            data_found = False
            if default_from and data_obj.browse(cr, uid, default_from) and data_obj.browse(cr, uid, default_from).name:
                default_from_header = data_obj.browse(cr, uid, default_from).name
                data_found = True
                val_data.append(('name', '>=', default_from_header))
            if default_to and data_obj.browse(cr, uid, default_to) and data_obj.browse(cr, uid, default_to).name:
                default_to_header = data_obj.browse(cr, uid, default_to).name
                data_found = True
                val_data.append(('name', '<=', default_to_header))
            if data_found:
                data_header = '"' + default_from_header + '" - "' + default_to_header + '"'
                data_ids = data_obj.search(cr, uid, val_data, order='id ASC')
        if filter_selection == 'input':
            data_found = False
            if input_from:
                data_ids_from = data_obj.search(cr, uid, [('name','=ilike',input_from + '%')], order="name", limit=1)
                if data_ids_from:
                    input_from_name = data_obj.browse(cr, uid, data_ids_from[0]).name
                    data_found = True
                    val_data.append(('name', '>=', input_from_name))
            if input_to:
                data_ids_to = data_obj.search(cr, uid, [('name','=ilike', input_to + '%')], order="name desc", limit=1)
                if data_ids_to:
                    input_to_name = data_obj.browse(cr, uid, data_ids_to[0]).name
                    data_found = True
                    val_data.append(('name', '<=', input_to_name))
            data_header = '"' + input_from + '" - "' + input_to + '"'
            if data_found:
                data_ids = data_obj.search(cr, uid, val_data, order='id ASC')
        if filter_selection == 'selection':
            if selection_ids:
                sel_ids = ''
                for sel in  data_obj.browse(cr, uid, selection_ids):
                    sel_ids += ('"%s",')%(sel.name,)

                data_header = '[' + sel_ids +']'
                data_ids = selection_ids
        return data_header, data_ids

    def _build_contexts(self, cr, uid, ids, data, context=None):
        if context is None:
            context = {}
        result = {}
        result['date_filter_selection'] = data['form']['date_filter_selection'] or False
        result['im_filter_selection'] = data['form']['im_filter_selection'] or False
        result['requestor_filter_selection'] = data['form']['requestor_filter_selection'] or False
        result['project_filter_selection'] = data['form']['project_filter_selection'] or False
        result['cust_filter_selection'] = data['form']['cust_filter_selection'] or False
        result['sortby_ids'] = data['form']['sortby_ids'] or False
        
        result['output_im_header'], result['im_ids'] = self._search_data(cr, uid, ids, self.pool.get('stock.picking'),
                                                                                      [('picking_type_id.code','=','internal'),('state','!=','cancel'),('gate_pass','=',True)],
                                                                                      data['form']['im_filter_selection'],
                                                                                      data['form']['im_def_from'] or False,
                                                                                      data['form']['im_def_to'] or False,
                                                                                      data['form']['im_input_from'] or False,
                                                                                      data['form']['im_input_to'] or False,
                                                                                      data['form']['im_no_ids'] or False,
                                                                                      context=context)

        result['output_requestor_header'], result['requestor_ids'] = self._search_data(cr, uid, ids, self.pool.get('res.users'),
                                                                                      [],
                                                                                      data['form']['requestor_filter_selection'],
                                                                                      data['form']['requestor_def_from'] or False,
                                                                                      data['form']['requestor_def_to'] or False,
                                                                                      data['form']['requestor_input_from'] or False,
                                                                                      data['form']['requestor_input_to'] or False,
                                                                                      data['form']['requestor_name_ids'] or False,
                                                                                      context=context)
        
        result['output_project_header'], result['project_ids'] = self._search_data(cr, uid, ids, self.pool.get('project.project'),
                                                                                      [('state', '!=', 'cancelled')],
                                                                                      data['form']['project_filter_selection'],
                                                                                      data['form']['project_def_from'] or False,
                                                                                      data['form']['project_def_to'] or False,
                                                                                      data['form']['project_input_from'] or False,
                                                                                      data['form']['project_input_to'] or False,
                                                                                      data['form']['project_name_ids'] or False,
                                                                                      context=context)
        
        result['output_cust_header'], result['cust_ids'] = self._search_data(cr, uid, ids, self.pool.get('res.partner'),
                                                                                      [],
                                                                                      data['form']['cust_filter_selection'],
                                                                                      data['form']['cust_def_from'] or False,
                                                                                      data['form']['cust_def_to'] or False,
                                                                                      data['form']['cust_input_from'] or False,
                                                                                      data['form']['cust_input_to'] or False,
                                                                                      data['form']['cust_name_ids'] or False,
                                                                                      context=context)
                
        date_from = data['form']['date_from']
        date_to = data['form']['date_to']
        
        output_date_header = ''
        val_date = []
        if data['form']['date_filter_selection'] == 'date_sel':
            if date_from and not date_to:
                output_date_header = 'Date Start From : %s' % (date_from,)
                val_date.append(('date','>=',str(date_from)))
            elif date_to and not date_from:
                output_date_header = 'Date Until : %s' % (date_to,)
                val_date.append(('date','<=',str(date_to))) 
            elif date_to and date_from:
                output_date_header = 'Date Start From : %s, Until: %s' % (date_from, date_to)
                val_date.append(('date','>=',str(date_from)))
                val_date.append(('date','<=',str(date_to)))

        result['output_date_header'] = output_date_header
        result['val_date'] = val_date
        
        return result
    
    def create_vat(self, cr, uid, ids, context=None):
        if context is None:
            context = {}
        datas = {'ids': context.get('active_ids', [])}
        datas['model'] = 'param.gatepass.report'
        datas['form'] = self.read(cr, uid, ids)[0]
        return {
            'type': 'ir.actions.report.xml',
            'report_name': 'gatepass.report_landscape',
            'datas': datas,
            'nodestroy':True,
        }
    
    def print_report(self, cr, uid, ids, context=None):
        if context is None:
            context = {}
        data = {}
        data['ids'] = context.get('active_ids', [])
        data['model'] = context.get('active_model', 'ir.ui.menu')
        data['form'] = self.read(cr, uid, ids, ['im_filter_selection','im_def_from','im_def_to','im_input_from','im_input_to', 'im_no_ids', \
                                                'requestor_filter_selection','requestor_def_from','requestor_def_to','requestor_input_from','requestor_input_to', 'requestor_name_ids', \
                                                'project_filter_selection','project_def_from','project_def_to','project_input_from','project_input_to', 'project_name_ids', \
                                                'cust_filter_selection','cust_def_from','cust_def_to','cust_input_from','cust_input_to', 'cust_name_ids', \
                                                'date_filter_selection', 'date_from', 'date_to', 'sortby_ids'], context=context)[0]
        for field in ['im_filter_selection','im_def_from','im_def_to','im_input_from','im_input_to', 'im_no_ids', \
                      'requestor_filter_selection','requestor_def_from','requestor_def_to','requestor_input_from','requestor_input_to', 'requestor_name_ids', \
                      'project_filter_selection','project_def_from','project_def_to','project_input_from','project_input_to', 'project_name_ids', \
                      'cust_filter_selection','cust_def_from','cust_def_to','cust_input_from','cust_input_to', 'cust_name_ids', \
                      'date_filter_selection', 'date_from', 'date_to', 'sortby_ids']:
            if isinstance(data['form'][field], tuple):
                data['form'][field] = data['form'][field][0]   
        used_context = self._build_contexts(cr, uid, ids, data, context=context)

        return self._get_tplines_xls(cr, uid, ids, used_context, context=context)
        
    def _get_tplines_xls(self, cr, uid, ids, form, context):

        if not ids:
            ids = data['ids']
        if not ids:
            return []
        
        user_obj            = self.pool.get('res.users')
        stock_move_obj      = self.pool.get('stock.move')
        stock_picking_obj   = self.pool.get('stock.picking')
        transfer_sortby_obj = self.pool.get('param.gatepass.report.sortby')
        
        result       = []
        results      = []
        val_transfer = [('picking_type_id.code','=','internal'),('state','!=','cancel'),('gate_pass','=',True),('project_id2.state','!=','cancelled')]
        
        im_ids = form['im_ids']
        requestor_ids = form['requestor_ids']
        project_ids = form['project_ids']
        cust_ids = form['cust_ids']
        
        output_date_header = form['output_date_header']
        output_im_header = form['output_im_header']
        output_requestor_header = form['output_requestor_header']
        output_project_header = form['output_project_header']
        output_cust_header = form['output_cust_header']
        
        output_sortby_header = ''

        if im_ids:
            val_transfer.append(('id','in',im_ids))
        if requestor_ids:
            val_transfer.append(('requestor_id','in',requestor_ids))
        if project_ids:
            val_transfer.append(('project_id2','in',project_ids))
        if cust_ids:
            val_transfer.append(('project_id2.analytic_account_id.partner_id','in',cust_ids)) 
        if 'val_date' in form:
            val_transfer += form['val_date']
        
        transfer_sortby_ids = []
        if 'sortby_ids' in form:
            transfer_sortby_ids = transfer_sortby_obj.search(cr, uid, [('id', 'in', form['sortby_ids'])], order='seq desc')
        
        if transfer_sortby_ids:
            for item in transfer_sortby_obj.browse(cr, uid, transfer_sortby_ids):
                result.append({
                        'seq' : item['seq'],
                        'sort_by' : item['sort_by'],
                        })
            result = result and sorted(result, key=lambda val_res: val_res['seq']) or []               
            
            for rs in result:
                sort_name = ''
                if rs['sort_by'] == 'date':
                    sort_name = 'Date'
                elif rs['sort_by'] == 'im_no':
                    sort_name = 'GP No'
                elif rs['sort_by'] == 'requestor_name':
                    sort_name = 'Requestor'
                elif rs['sort_by'] == 'project_name':
                    sort_name = 'Project'
                elif rs['sort_by'] == 'cust_name':
                    sort_name = 'Customer'
                output_sortby_header += ('"%s",')%(sort_name,)
        
        transfer_ids = stock_picking_obj.search(cr, uid, val_transfer)
        
        if transfer_ids:
            transfer_im_ids = []
            
            for im in stock_picking_obj.browse(cr, uid, transfer_ids):
                move_lines = []
                move_lines_ids = stock_move_obj.search(cr, uid,[('picking_id','=',im.id)])
                for sml in stock_move_obj.browse(cr, uid, move_lines_ids, context=None) :
                    move_lines.append({  
                        'description' : sml.name,
                        'product_qty' : sml.product_uom_qty,
                        'product_uom': sml.product_uom.name,
                       })
                
                transfer_im_ids.append({
                    'date' : im.date,
                    'im_no' : im.name,
                    'requestor_name' : im.requestor_id.name,
                    'project_name' : im.project_id2.name,
                    'cust_name' : im.project_id2.analytic_account_id.partner_id.name,
                    'remark': im.remark,
                    'move_lines': move_lines,
                })
                
            if transfer_sortby_ids:
                for transfer_sortby in transfer_sortby_obj.browse(cr, uid, transfer_sortby_ids):
                    transfer_im_ids = transfer_im_ids and sorted(transfer_im_ids, key=lambda val_res: val_res[transfer_sortby.sort_by]) or []               
            else:
                transfer_im_ids = transfer_im_ids and sorted(transfer_im_ids, key=lambda val_res: val_res['cust_name']) or []
                transfer_im_ids = transfer_im_ids and sorted(transfer_im_ids, key=lambda val_res: val_res['project_name']) or []
                transfer_im_ids = transfer_im_ids and sorted(transfer_im_ids, key=lambda val_res: val_res['requestor_name']) or []
                transfer_im_ids = transfer_im_ids and sorted(transfer_im_ids, key=lambda val_res: val_res['im_no']) or []
                transfer_im_ids = transfer_im_ids and sorted(transfer_im_ids, key=lambda val_res: val_res['date']) or []
            
            for transfer_result in transfer_im_ids:
                results.append({
                    'date' : transfer_result['date'] or '',
                    'im_no' : transfer_result['im_no'] or '',
                    'requestor_name' : transfer_result['requestor_name'] or '',
                    'project_name' : transfer_result['project_name'] or '',
                    'cust_name' : transfer_result['cust_name'] or '',
                    'remark' : transfer_result['remark'] or '',
                    'move_lines' : transfer_result['move_lines'] or '',
                })
           
        workbook = xlwt.Workbook()
        M_header_tstyle = format_common.font_style(position='center', bold=1, border=3, fontos='black', font_height=300)
        report_tstyle = format_common.font_style(position='left', bold=1, fontos='black', font_height=190)
        report_tstyle1 = format_common.font_style(position='left', bold=1, fontos='black', font_height=180)
        header_tstyle = format_common.font_style(position='right', bold=1, fontos='black', font_height=180)
        header_tstyle_c = format_common.font_style(position='center', bold=1, border=1, fontos='black', font_height=160)
        header_tstyle_l = format_common.font_style(position='left', bold=1,border=1, fontos='black', font_height=180)
        header_tstyle_c_Top = format_common.font_style(position='center', bold=1, border=4, fontos='black', font_height=180)
        header_tstyle_c_Bottom = format_common.font_style(position='center', bold=1, border=3, fontos='black', font_height=180)
        header_tstyle_r = format_common.font_style(position='right', bold=1,  border=1,fontos='black', font_height=180)
        view_tstyle = format_common.font_style(position='left', fontos='black', font_height=180)
        view_tstyle_c = format_common.font_style(position='center', border=1, fontos='black', font_height=150)
        view_tstyle_l = format_common.font_style(position='left',border=1, fontos='black', font_height=150)
        view_tstyle_r = format_common.font_style(position='right', border=1, fontos='black', font_height=180)
        view_tstyle_r_b = format_common.font_style(position='right', bold=1, fontos='black', font_height=180)
        other_tstyle = format_common.font_style(position='left', fontos='black', font_height=180)
        other_tstyle_c = format_common.font_style(position='center', fontos='black', font_height=180)
        other_tstyle_r = format_common.font_style(position='right', fontos='black', font_height=180)
        text_tstyle = format_common.font_style(position='left', bold=1, border=1, fontos='black', font_height=180)
        text_tstyle1 = format_common.font_style(position='left', bold=1, fontos='black', font_height=220)
        text_tstyle2 = format_common.font_style(position='left', fontos='black', font_height=220)
        text_tstyle_c = format_common.font_style(position='center', bold=1, fontos='black', font_height=180)
        text_tstyle_l = format_common.font_style(position='left', bold=1, fontos='black', font_height=180)
        text_tstyle_r = format_common.font_style(position='right', bold=1, fontos='black', font_height=180)
        text_tstyle_r_closing = format_common.font_style(position='right', bold=1,border=7, fontos='black', font_height=180)
        text_tstyle_Top = format_common.font_style(position='left', bold=1, border=4, fontos='black', font_height=180)
        text_tstyle_Bottom = format_common.font_style(position='left', bold=1, border=3, fontos='black', font_height=180)
        text_tstyle_Top_r = format_common.font_style(position='right', bold=1, border=4, fontos='black', font_height=180)
        text_tstyle_Top_l = format_common.font_style(position='left', bold=1, border=4, fontos='black', font_height=180)
        text_tstyle_Top_r_r = format_common.font_style(position='right', bold=1, border=6, fontos='black', font_height=180)
        text_tstyle_Top_l_l = format_common.font_style(position='left', bold=1, border=6, fontos='black', font_height=180)
        text_tstyle_Bottom_r = format_common.font_style(position='right', bold=1, border=3, fontos='black', font_height=180)
        text_tstyle_TopBottom = format_common.font_style(position='left', bold=1, border=2, fontos='black', font_height=180)
        text_tstyle_TopBottom_r = format_common.font_style(position='right', bold=1, border=2, fontos='black', font_height=180)
        
        sheet = workbook.add_sheet('Gatepass Report XLS')
        sheet.row(0).height = 350
        row=0
        
        company_name = user_obj.browse(cr, uid, uid).company_id.name
        sheet.write_merge(row, row, 0, 8, company_name, report_tstyle1)
        
        row+=1
        sheet.write_merge(row, row, 0, 8, 'Gate Pass Report', report_tstyle1)
        
        user_ids = user_obj.search(cr, uid, [('id','=',uid)])
        if user_ids :
            tz = user_obj.browse(cr, uid, user_ids[0])
            tz_name = tz.tz
            user_name = tz.name
            
        os.environ['TZ'] = tz_name
        time.tzset()
        
        row+=1
        sheet.write_merge(row, row, 0, 2, 'Printed date : ' + time.strftime("%Y/%m/%d") + '  Time : '+ time.strftime("%H:%M:%S"), view_tstyle)
        sheet.write_merge(row, row, 3, 5, 'Printed by : ' + user_name, view_tstyle)
        
        row+=1
        sheet.write(row, 0, '', view_tstyle)
        
        if form['date_filter_selection'] != 'none_sel':
            row += 1
            sheet.write_merge(row, row, 0, 8, '   ' + output_date_header, report_tstyle1)
        
        if form['im_filter_selection'] != 'all_vall':
            row += 1
            sheet.write_merge(row, row, 0, 8, '   GP No. : ' + output_im_header, report_tstyle1)
        
        if form['requestor_filter_selection'] != 'all_vall':
            row += 1
            sheet.write_merge(row, row, 0, 8, '   Requestor : ' + output_requestor_header, report_tstyle1)
        
        if form['project_filter_selection'] != 'all_vall' :
            row += 1
            sheet.write_merge(row, row, 0, 8, '   Project : ' + output_project_header, report_tstyle1)
        
        if form['cust_filter_selection'] != 'all_vall' :
            row += 1
            sheet.write_merge(row, row, 0, 8, '   Customer : ' + output_cust_header, report_tstyle1)
        
        if form['sortby_ids']:
            row += 1
            sheet.write_merge(row, row, 0, 8, '   Sort By : ' + output_sortby_header, report_tstyle1)
         
        sheet.col(0).width = 256 * 12
        sheet.col(1).width = 256 * 14
        sheet.col(2).width = 256 * 15
        sheet.col(3).width = 256 * 28
        sheet.col(4).width = 256 * 20
        sheet.col(5).width = 256 * 28
        sheet.col(6).width = 256 * 10
        sheet.col(7).width = 256 * 8
        sheet.col(8).width = 256 * 20
        
        for rs1 in results:  
            row+=2
            sheet.write(row, 0, 'Date', header_tstyle_c)
            sheet.write(row, 1, 'GP No.', header_tstyle_c)
            sheet.write(row, 2, 'Requestor', header_tstyle_c)
            sheet.write(row, 3, 'Project Name', header_tstyle_c)
            sheet.write(row, 4, 'Customer', header_tstyle_c)
            sheet.write(row, 5, 'Description', header_tstyle_c)
            sheet.write(row, 6, 'Quantity', header_tstyle_c)
            sheet.write(row, 7, 'UOM', header_tstyle_c)
            sheet.write(row, 8, 'Remark', header_tstyle_c)
            
            for rs2 in rs1['move_lines']:
                row += 1
                sheet.write(row, 0, str(rs1['date'][:10]), view_tstyle_l)
                sheet.write(row, 1, str(rs1['im_no']), view_tstyle_l)
                sheet.write(row, 2, str(rs1['requestor_name']), view_tstyle_l)
                sheet.write(row, 3, str(rs1['project_name']), view_tstyle_l)
                sheet.write(row, 4, str(rs1['cust_name']), view_tstyle_l)
                sheet.write(row, 5, str(rs2['description']), view_tstyle_l)
                sheet.write(row, 6, str(rs2['product_qty']), view_tstyle_r)
                sheet.write(row, 7, str(rs2['product_uom']), view_tstyle_l)
                sheet.write(row, 8, str(rs1['remark']), view_tstyle_l)
        
        row+=1
        sheet.write(row, 0, '', view_tstyle)
        
        row += 1
        sheet.write_merge(row, row, 0, 8, 'End of Report', text_tstyle_Top_l) 
        
        stream = cStringIO.StringIO()
        workbook.save(stream)
            
        cr.execute(""" DELETE FROM output""")
        attach_id = self.pool.get('output').create(cr, uid, {'name':'Gatepass Report.xls', 'xls_output':base64.encodestring(stream.getvalue())})
        return {
                'name': _('Notification'),
                'context': context,
                'view_type': 'form',
                'view_mode': 'form',
                'res_model': 'output',
                'res_id':attach_id,
                'type': 'ir.actions.act_window',
                'target':'new'
                }

class param_gatepass_report_sortby(osv.osv_memory):
    
    _name = "param.gatepass.report.sortby"
    
    _columns = {
        'sortby_id': fields.many2one('param.gatepass.report', 'Sort By', required=True, ondelete='cascade'),
        'seq': fields.integer('Sequence', required=True),
        'sort_by': fields.selection([('date','Date'),('im_no', 'GP No'), ('requestor_name', 'Requestor'), ('project_name', 'Project'), ('cust_name', 'Customer')],'Sort by', required=True),
    }
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
